package com.wang.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

/**
 * Servlet implementation class DownLoad
 */
@WebServlet("/download")
public class DownLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String parameter = request.getParameter("fileName");
		String realPath = request.getServletContext().getRealPath("/download");
		File file = new File(realPath,parameter);
		if(file.exists()){
			//设置下载类型
			if(request.getHeader("User-Agent").toLowerCase().indexOf("tridend") != -1){
				parameter = URLEncoder.encode(parameter, "utf-8");
			}else if(request.getHeader("User-Agent").toLowerCase().indexOf("edge") != -1){
				parameter = URLEncoder.encode(parameter, "utf-8");
			}else{
				parameter = new String(parameter.getBytes("utf-8"),"ISO-8859-1");
			}
			response.setHeader("Content-Disposition", "attchment;filename="+parameter);
			//创建文件输入字节流
			FileInputStream fileInputStream = new FileInputStream(file);
			//通过响应对象获取输出流
			ServletOutputStream outputStream = response.getOutputStream();
			int copy = IOUtils.copy(fileInputStream, outputStream);
			System.out.println(copy);
			outputStream.close();
			fileInputStream.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
